/**
 * 
 */
package com.hfjyz.registration.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hfjyz.registration.model.Master;

/**
 *
 */
public class MasterUtil {
	private static MasterUtil instance = new MasterUtil();
	private Map<Integer, List<Master>> masters = new HashMap<Integer, List<Master>>();

	private Map<Integer, Master> orignals = new HashMap<Integer, Master>();

	private MasterUtil() {
	}

	public static MasterUtil getInstance() {
		return instance;
	}

	public void init(List<Master> ms) {
		for (Master m : ms) {
			orignals.put(m.getId(), m);
			List<Master> cms = masters.get(m.getCategory());
			if (cms == null) {
				cms = new ArrayList<Master>();
				masters.put(m.getCategory(), cms);
			}
			cms.add(m);
		}
	}

	public List<Master> getMasters(int category) {

		List<Master> ms = masters.get(category);
		if (ms == null) {
			return new ArrayList<Master>(0);
		}
		return new ArrayList<Master>(ms);
	}

	public String getMasterName(int category, String code) {
		List<Master> ms = masters.get(category);
		if (ms != null) {
			for (Master m : ms) {
				if (m.getCode().equals(code)) {
					return m.getName();
				}
			}
		}
		return "";
	}

	public String getMasterName(Integer id) {
		if (id == null) {
			return "";
		}
		Master m = orignals.get(id);
		if (m != null) {
			return m.getName();
		}
		return "";
	}

	public String getMasterName(String id) {
		if (id == null || id.length() == 0) {
			return "";
		}
		Master m = orignals.get(Integer.parseInt(id));
		if (m != null) {
			return m.getName();
		}
		return "";
	}

	public Master createTemp(int category) {
		Master master = new Master();
		master.setCategory(category);
		master.setId(-1);
		master.setCode("");
		master.setName("");
		return master;

	}

	public Master getMaster(Integer id) {
		return orignals.get(id);
	}

	public Master getMaster(Integer category, String code) {

		List<Master> ms = getMasters(category);
		for (Master m : ms) {
			if (m.getCode().equals(code)) {
				return m;
			}
		}
		return null;
	}
}
